package org.ouwh.fw.timer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TimerThread implements Runnable {
	private static Log log = LogFactory.getLog(TimerThread.class);

	private boolean running = false;

	private String name = "TimerThread";

	private ITimerTask task = null;

	private Thread thread = null;

	private long interval = 60000;

	private boolean isThreadDead = true;

	public void setName(String name) {
		this.name = name;
	}

	public void startup() throws Exception {
		if (task == null) {
			throw new Exception("Timer[" + name + "] no task");
		}
		running = true;
		thread = new Thread(this);
		thread.setDaemon(false);
		thread.setName(this.name);
		thread.start();
	}

	public void run() {
		isThreadDead = false;
		log.info("Timer[" + name + "]active.");
		while (running) {
			try {
				Thread.sleep(interval);
				if (running) {
					task.onTimer();
				}
			} catch (InterruptedException ie) {
				// do nothing
			} catch (Exception e) {
				log.error("Timer[" + name + "]execute error", e);
			}
		}
		log.info("Timer[" + name + "]cancelled.");
		isThreadDead = true;
	}

	public void shutdown() {
		this.running = false;
		try {
			task.interrupt();
		} catch (Exception e) {
			log.error("Timer[" + name + "]error in cancelling", e);
		}
		if (thread != null) {
			thread.interrupt();
		}
		while (!isThreadDead) {
			try {
				Thread.sleep(100);
			} catch (Exception e) {
			}
		}
	}

	public void setTask(ITimerTask task) {
		this.task = task;
	}

	public void setInterval(long interval) {
		this.interval = interval;
	}

	public long getInterval() {
		return this.interval;
	}

	public String getTaskInfo() {
		return task.getInfo();
	}

	public String getName() {
		return name;
	}

	public boolean isRunning() {
		return running;
	}
}
